package com.xx.controller;

import com.xx.entity.Categories;
import com.xx.entity.R;
import com.xx.enums.HttpEnum;
import com.xx.service.CategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;


@Controller
@RequestMapping("/categories")
@CrossOrigin
public class CategoriesController {

    @Autowired
    CategoriesService categoriesService;

    @GetMapping
    public R queryByPage(Categories categories, Integer pageNum) {
        return R.success(categoriesService.queryByPage(categories, pageNum));
    }

    @GetMapping("{id}")
    public R queryById(@PathVariable("id") Integer id) {
        Categories categories = categoriesService.queryById(id);
        try{
            if (categories.getCategoryId() <= 0 || categories.getCategoryName() == null) {
                return R.fail(HttpEnum.WARN.getCode(), "没有该分类");
            }
            return R.success(categories);
        }catch (Exception e){
            return R.fail(HttpEnum.WARN.getCode(),e.getMessage());
        }
    }

    @PostMapping
    public R add(@RequestBody Categories categories) {
        if (categoriesService.insert(categories) > 0) {
            return R.success(categories);
        }
        return R.fail(HttpEnum.WARN.getCode(), "添加失败");
    }

    @PutMapping
    public R edit(@RequestBody Categories categories) {
        if (categoriesService.update(categories) > 0) {
            return R.success(categories);
        }
        return R.fail(HttpEnum.WARN.getCode(), "编辑失败");
    }

    @DeleteMapping("{id}")
    public R deleteById(@PathVariable("id") Integer id) {
        if (categoriesService.deleteById(id) > 0) {
            return R.success("删除成功");
        }
        return R.fail(HttpEnum.WARN.getCode(), "删除失败");
    }

    @GetMapping("list")
    public R list() {
        return R.success(categoriesService.list());
    }
}
